package com.cheyun.netsalev3.viewmodel

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.view.View
import com.cheyun.netsalev3.repository.LoginRepository
import android.view.Gravity
import android.view.ViewGroup
import android.view.LayoutInflater
import android.webkit.WebView
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import com.cheyun.netsalev3.R
import com.cheyun.netsalev3.bean.NameIdParam
import com.cheyun.netsalev3.bean.dms.DmsUser
import com.cheyun.netsalev3.utils.*
import com.cheyun.netsalev3.utils.api.ApiStores
import com.cheyun.netsalev3.widget.PopDialog
import java.util.ArrayList
import android.os.CountDownTimer
import android.widget.LinearLayout


/**
 * @author Michael
 * @date  2018/12/6 - 10:48.
 */
class RegisterActivityViewModel : BaseViewModel(),PopDialog.PopDialogListener {

    var mobile: String = ""
    var password: String = ""
    var confirmPassword: String = ""
    var code: String = ""
    var dlrCode: String = ""
    var realName: String = ""
    var customerCode:String = ""
    var idnumber:String = ""
    var customerName = ObservableField<String>("")

    private var loginRepository = LoginRepository()
    var showPwd = MutableLiveData<Boolean>()
    var showConfirmPwd = MutableLiveData<Boolean>()
    var activity: Activity? = null

    var customerlist = MutableLiveData<List<NameIdParam>>()

    var clist: List<DmsUser> = arrayListOf()

    private var dialog: PopDialog? = null

    var agree = MutableLiveData<Boolean>(false)

    init {
        var ys = MySharedPreferences.getYsChecked()
        agree.postValue(ys.equals("1"))
    }

    fun onClickRegister(view: View) {
        if (CommonFunc.isBlank(mobile)) {
            MyToast("请输入手机号")
            return
        }
        if (CommonFunc.isBlank(code)) {
            MyToast("请输入验证码")
            return
        }
        if (CommonFunc.isBlank(password)) {
            MyToast("请输入登录密码")
            return
        }
        if(password.length<8 || password.length > 50){
            MyToast("密码请在8-50位之间")
            return
        }
        if(!CommonFunc.checkPwd(password)){
            MyToast("密码必须包含大写字母、小写字母、数字、特殊符号中的其中3种")
            return
        }
        if(CommonFunc.isBlank(confirmPassword)){
            MyToast("请输入确认密码")
            return
        }
        if(!password.equals(confirmPassword)){
            MyToast("两次输入的密码不一致，请确认")
            return
        }
        if(CommonFunc.isBlank(realName)){
            MyToast("请输入名称")
            return
        }
        if(CommonFunc.isBlank(dlrCode)){
            MyToast("请输入经销商代码")
            return
        }
        if(CommonFunc.isBlank(idnumber)){
            MyToast("请输入身份证号")
            return
        }
//        if(CommonFunc.isBlank(customerCode)){
//            MyToast("请选择DMS账号")
//            return
//        }
        if (!agree.value!!) {
            MyToast("请阅读并同意隐私协议")
            return
        }
//        var cname = "";
//        for(user in clist){
//            if(user.UserName.equals(customerCode)){
//                cname = user.Ename
//            }
//        }

        loginRepository.register(mobile, password,realName,code,dlrCode,idnumber, this::setData)
    }
    fun onPasViewClick(view:View){
        this.showPwd.postValue(!showPwd.value!!)
    }

    fun onConfirmPasViewClick(view:View){
        this.showConfirmPwd.postValue(!showConfirmPwd.value!!)
    }

    private var view:View? = null
    fun onCustomerClick(view:View){
        if(CommonFunc.isBlank(dlrCode)){
            MyToast("请输入经销商代码")
            return
        }
        this.view = view
        loginRepository.getDmsUser(dlrCode,this::setDmsUser)
    }

    fun onBack(view:View){
        this.myFinish()
    }

    fun onSendCodeClick(view:View){
        if (CommonFunc.isBlank(mobile)) {
            MyToast("请输入手机号")
            return
        }
        if(currentTime==0L) {
            loginRepository.getPhoneCode("register", "send", mobile, this::setCode)
        }
    }

    /**
     * 登陆请求数据回调
     */
    fun setData(param: Any) {
        this.activity?.finish()
        MyToast("注册成功,请等待审核")
    }

    fun setDmsUser(list: List<DmsUser>) {
        clist = list
        var temlist4 = ArrayList<NameIdParam>()
        for(user in list){
            temlist4.add(NameIdParam(user.Ename+"("+user.UserName+")", user.id.toString(),0,user.UserName))
        }
        customerlist.postValue(temlist4)
        var context = this.view?.context
        if (context is AppCompatActivity) {
            if (dialog == null) {
                dialog = PopDialog()
                dialog!!.listener = this
            }
            dialog?.show(context.supportFragmentManager, "pop")
        }
    }

    fun setCode(param: Any) {
        MyToast("验证码已发送")
        countDownTimer.start()
    }

    var totalTime = 60000L
    var oneceTime = 1000L
    var showTime = MutableLiveData<String>()
    var currentTime = 0L
    private val countDownTimer = object : CountDownTimer(totalTime, oneceTime) {
        override fun onTick(millisUntilFinished: Long) {
            val value = (millisUntilFinished / 1000).toInt().toString()
            currentTime = millisUntilFinished/1000
            showTime.postValue(value)
        }

        override fun onFinish() {
            currentTime = 0
            showTime.postValue("0")
        }
    }

    fun login(view:View) {
        this.activity?.finish()
    }

    fun showYs(view:View){
//        val bottomDialog = Dialog(view.context, R.style.BottomDialog)
//        val contentView = LayoutInflater.from(view.context).inflate(R.layout.dialog_content_circle, null)
//        bottomDialog.setContentView(contentView)
//        val webView = contentView.findViewById<WebView>(R.id.detail_webview)
//        webView.settings.javaScriptEnabled = true
//        webView.settings.domStorageEnabled = true
//        webView.loadUrl(ApiStores.XIEYI_URL)
//        val params = contentView.getLayoutParams() as ViewGroup.MarginLayoutParams
//        params.width = view.context.getResources().getDisplayMetrics().widthPixels - FunctionUtils.dip2px(view.context, 16f)
//        params.bottomMargin = FunctionUtils.dip2px(view.context, 8f)

//        contentView.setLayoutParams(params)
//        bottomDialog.getWindow().setGravity(Gravity.BOTTOM)
//        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation)
//        bottomDialog.show()
        val bottomDialog = Dialog(view.context, R.style.BottomDialog)
        val contentView = LayoutInflater.from(view.context).inflate(R.layout.dialog_content_circle, null)
        bottomDialog.setContentView(contentView)
        val params = contentView.getLayoutParams() as ViewGroup.MarginLayoutParams
        params.width = view.context.getResources().getDisplayMetrics().widthPixels - FunctionUtils.dip2px(view.context, 16f)
        params.bottomMargin = FunctionUtils.dip2px(view.context, 8f)
        contentView.setLayoutParams(params)
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM)
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation)
        bottomDialog.show()

        var llWin = contentView.findViewById<LinearLayout>(R.id.ll_win)
        llWin.setOnClickListener { bottomDialog.dismiss() }
    }

    fun onAgree(view: View) {
        agree.postValue(!agree.value!!)
    }

    override var list: MutableLiveData<List<NameIdParam>>
        get(){
            return customerlist
        }
        set(value) {list = value}
    override var dialogType: MutableLiveData<String>
        get() {return MutableLiveData("请选择")}
        set(value) {}
    override var dialogTitle: MutableLiveData<String>
        get() {return MutableLiveData("list")}
        set(value) {}

    override fun onClickItem(view: View, param: NameIdParam) {
        customerlist.value?.apply {
            for (item in this) {
                item.IsSelect = param.value.equals(item.value)
            }
        }
        customerCode = param.value!!
        customerName.set(param.name)

        dialog?.dismiss()

    }

    override fun onDialogSubmit(view: View, param: String) {
        TODO("Not yet implemented")
    }
}